package handdraw;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.List;

public class HandDraw extends JPanel {

    private boolean pressed = false;
    private List<Cruve> cruveList = new ArrayList<>();
    public HandDraw() {
        this.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {

            }

            @Override
            public void mousePressed(MouseEvent e) {
                pressed = true;
                //创建一条新的曲线
                Cruve cruve = new Cruve();
                cruveList.add(cruve);
                cruve.points.add(e.getPoint());//记录鼠标的位置
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                pressed = false;
            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseExited(MouseEvent e) {

            }
        });

        this.addMouseMotionListener(new MouseMotionListener() {
            @Override
            public void mouseDragged(MouseEvent e) {
                if (pressed){
                    //当前的笔画就是列表中的最后一条
                    Cruve cruve = cruveList.get(cruveList.size()-1);
                    cruve.points.add(e.getPoint());
                    repaint();
                }
            }

            @Override
            public void mouseMoved(MouseEvent e) {

            }
        });

    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        int width = this.getWidth();
        int height = this.getHeight();

        g.setColor(new Color(0xFFFFF0));
        g.fillRect(0,0,width,200);

        for (Cruve cruve:cruveList){
            List<Point> points = cruve.points;
            if (points.size()>+2){
                //设置线条颜色
                g.setColor(Color.RED);

                //开始绘制,每个点连接在一起形成一条曲线
                Point p1 = points.get(0);
                for (int i = 0; i < points.size(); i++) {
                    Point p2 = points.get(i);
                    g.drawLine(p1.x,p1.y,p2.x,p2.y);

                    p1 = p2;
                }
            }
        }

    }

    private static class Cruve{
        public List<Point> points = new ArrayList<>();
    }
}
